package hyj.qx.kuaican.service.impl;

import hyj.qx.kuaican.exception.BusinessException;
import hyj.qx.kuaican.model.*;
import hyj.qx.kuaican.service.OrderRepository;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import static hyj.qx.kuaican.model.Item.getPriceById;

public class OrderService {
    // 主食类
    OrderRepository orderRepository = new MemoryOrderRepository();

    // 创建订单（核心方法）
    public Order createOrder(List<Item> items, boolean isVIP) throws BusinessException {
        Order order = new Order();
        int mainCount = 0;
        double totalPrice = 0.0;
        LocalTime now = LocalTime.now();
        String remark = null;

        // 1. 预处理：过滤无效商品（如下架的冰咖啡）
        List<Item> validItems = new ArrayList<>();
        for (Item item : items) {
            // 检查冰咖啡是否下架
            if (ItemType.DRINK.equals(item.getType())) {
                if ("冰咖啡".equals(item.getName()) && now.isAfter(LocalTime.of(15, 0))) {
                    remark = "冰咖啡已下架";
                    continue; // 跳过下架商品
                }
            }
            validItems.add(item);
        }

        // 2. 校验商品数量（基于过滤后的有效商品）
        if (validItems.size() > 5) {
            throw new BusinessException(ErrorCode.CAO_DINDANFW);
        }

        // 3. 检查汉堡+薯条套餐优惠
        boolean hasBurger = validItems.stream().anyMatch(i -> "汉堡".equals(i.getName()));
        boolean hasFries = validItems.stream().anyMatch(i -> "薯条".equals(i.getName()));
        if (hasBurger && hasFries) {
            totalPrice -= 5.0;
        }

        // 4. 处理饮料第二杯半价（仅基于有效商品）
        Map<String, Long> drinkCounts = validItems.stream().filter(i -> ItemType.DRINK.equals(i.getType())).collect(Collectors.groupingBy(Item::getId, Collectors.counting()));
        double drinkTotal = 0.0;
        for (Map.Entry<String, Long> entry : drinkCounts.entrySet()) {
            String id = entry.getKey();
            long count = entry.getValue();
            double price = getPriceById(id);
            long fullPairs = count / 2;
            long singleCups = count % 2;
            drinkTotal += (fullPairs * 1.5 * price) + (singleCups * price);
        }
        totalPrice += drinkTotal;

        // 5. 处理主食和其他商品价格
        for (Item item : validItems) {
            // 跳过已处理的饮料
            if (ItemType.DRINK.equals(item.getType())) {
                continue;
            }

            totalPrice += item.getPrice();

            // 统计主食数量
            if (ItemType.MAIN.equals(item.getType())) {
                mainCount++;
            }
        }

        if (mainCount == 0) {
            throw new BusinessException(ErrorCode.NO_MAIN_DISH);
        }
        if (isVIP) {
            totalPrice *= 0.9;
        }

        // 7. 生成订单
        order.setOrderId(UUID.randomUUID().toString().substring(0, 8));
        order.setCreateTime(LocalDateTime.now());
        order.setItems(validItems);
        order.setStatus(OrderStatus.CREATED);
        order.setTotalPrice(totalPrice);
        if (remark != null) {
            order.setRemark(remark);
        }
        orderRepository.save(order);
        return order;
    }

    // 取消订单
    public void cancelOrder(String orderId) throws BusinessException {
        // TODO 实现状态校验与超时处理
        Order order = orderRepository.findById(orderId);
        if (order.getStatus().equals(OrderStatus.CANCELLED)) {
            throw new BusinessException(ErrorCode.ORDER_ISKO);
        }
        if (order.getStatus().equals(OrderStatus.PAID)) {
            throw new BusinessException(ErrorCode.YIJIN_ZHIFU);
        }
        orderRepository.updateStatus(orderId, OrderStatus.CANCELLED);
    }

    public Order getOrder(String OrderId) throws BusinessException {
        Order order = orderRepository.findById(OrderId);
        if (order == null) {
            throw new BusinessException(ErrorCode.NOT_ORDER);
        }
        if (order.getStatus() == OrderStatus.CREATED) {
            LocalDateTime createTime = order.getCreateTime();
            LocalDateTime currentTime = LocalDateTime.now();
            Duration duration = Duration.between(createTime, currentTime);
            if (duration.toMinutes() > 30) {
                orderRepository.updateStatus(OrderId, OrderStatus.CANCELLED);
            }

        }
        return orderRepository.findById(OrderId);
    }

    public Order updateOrder(String orderId, List<Item> allItems, List<Item> addItems, List<Item> reItems, boolean vip) throws BusinessException {
        Order order = getOrder(orderId);
        if (order == null) {
            throw new BusinessException(ErrorCode.NOT_ORDER);
        }
        if (order.getStatus() != OrderStatus.CREATED) {
            throw new BusinessException(ErrorCode.MODIFY_FORBIDDEN);
        }
        CyOrder cyOrder = new CyOrder();
        cyOrder.setOrderId(orderId);
        List<Item> items = order.getItems();
        if (!allItems.isEmpty()) {
            //全改
            List<Item> yItems = new ArrayList<>(items); // 备份原始列表
            items.removeAll(items);
            items.addAll(allItems);
            cyOrder.setRemoveItems(yItems); // 记录被移除的原始条目
            cyOrder.setAddItems(allItems); // 记录添加的新条目
        }
        //部分改

        if (!addItems.isEmpty()) {
            items.addAll(addItems);
            cyOrder.setAddItems(addItems);
        }
        if (!reItems.isEmpty()) {
            for (Item item : reItems) {
                items.remove(item);
            }
            cyOrder.setRemoveItems(reItems);
        }
        Order order1 = createOrder(items, vip);
        cyOrder.setOrderId(orderId);
        cyOrder.setyMoney(order.getTotalPrice());
        cyOrder.setxMoney(order1.getTotalPrice());
        orderRepository.addCyOrderMap(orderId, cyOrder);//记录修改差异单
        orderRepository.addOrderMap(orderId, order1);//修改订单

        return order1;
    }

    public List<CyOrder> getCyOrder() throws BusinessException {
        List<CyOrder> ok = orderRepository.findCyOrder();
        if (ok == null) {
            throw new BusinessException(ErrorCode.NOT_ORDER);
        }
        return ok;
    }


}
